package com.gzj.springboot.controller;

import com.gzj.springboot.mapper.UserMapper;
import com.gzj.springboot.domain.User;
import com.gzj.springboot.service.Userservice;
import com.gzj.springboot.tools.Data_Processing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.thymeleaf.util.StringUtils;

//import java.beans.BeanProperty;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 实现的方法处要填加注解：
 * 如果使用@Controller注解需要在方法处加 @ResponseBody
 * 也可以直接用@RestController下面方法处就不用加别的注解了
 */
@Controller
public class MybatisController {

     Data_Processing data_processing = new Data_Processing();
    /**
     * 最开始希望用Map的形式接参数，后来不用了，将请求对应的接受方式记录一下
     *
     * @RequestBody Map<String,Object> map      post请求
     * @RequestParam Map<String,Object> map     get请求
     */


    @Autowired  //该注释是说明需要外部资源（自动装配）
    private UserMapper userMapper;

    /**
     * 注入service
     */
    @Autowired
    private Userservice userservice;
    private Object object;

    /**
     * 同时这个时候可以自己了解一下@Controller与@RestController的区别，以及@ResponseBody的用法。
     */

//    /**
//     * 查询所以用户信息
//     * @return
//     */
//    @RequestMapping("/aaa")
//    @ResponseBody
//    public List<User> ListqueryUserList(){
//        List<User> users = userMapper.queryUserList();
//        return users;
//    }


    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("/tologin.action")
    public String index(){
        return "login";
    }

    @RequestMapping(value = {"/toPhoto"})
    public String toPhoto(){
        return "index";
    }

    /**
     * 跳转到注册页面
     * @return
     */
    @RequestMapping(value = {"/registerpage"})
    public String registerpage(){
        return "register";
    }

    /**
     * 跳转到用户查询页面
     */
    @RequestMapping(value = {"/touserbyid"})
    public String userbyid(){
        return "detail";
    }


    /**
     * 用户登录
     * @param user_name
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "login.action")
    @ResponseBody
   public String userLogin(@RequestParam("user_name") String user_name,
                           @RequestParam("password") String password,
                           HttpServletRequest request){
            if (StringUtils.isEmpty(user_name)){
                return "用户名不能为空";
            }
            if (StringUtils.isEmpty(password)){
                return "密码不能为空";
            }
            User user = userservice.login(user_name,password);
            if (user !=null){                                                       //登录成功
                request.getSession().setAttribute("session_user",user);      //将用户信息放入session 用于后续的拦截器
                return "登录成功";
            }
            return "登录失败";
    }

    /**
     * 用户注册
     * @param user_name
     * @param password
     * @param password2
     * @param age
     * @param addr
     * @param name
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/uregister"})
    public String addUser(@RequestParam("user_name") String user_name, //获取页面user_name
                          @RequestParam("password") String password,
                          @RequestParam("password2") String password2,
                          @RequestParam("age") Integer age,
                          @RequestParam("addr") String addr,
                          @RequestParam("name") String name){
        if (StringUtils.isEmpty(user_name)){
            return"用户名不能为空";
        }
        if (StringUtils.isEmpty(password)){
            return "密码不能为空";
        }
        if (StringUtils.isEmpty(password2)){
            return "请输入确认密码";
        }
        if (!password.equals(password2)){
            return "两次密码不相同，注册失败！！";
        }else {
//            Data_Processing data_processing = new Data_Processing();
//            String id =data_processing.RandomCharacters();

            int res = userservice.adduser(user_name,password,age,addr,name);
            if (res == 0){
                return "注册失败,账号存在";
            }else {
                return "注册成功";
            }
        }
    }

    /**
     * 修改用户基本信息
     * @param user_name
     * @param age
     * @param addr
     * @param name
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/updateId"})
    public String updateId(@RequestParam("user_name") String user_name,
                           @RequestParam("age") Integer age,
                           @RequestParam("addr") String addr,
                           @RequestParam("name") String name){
        int res = userservice.updateId(name,age,addr,user_name);
        if (res == 0){
            return "更改失败";
        }else {
            return "更改成功";
        }
    }

    /**
     *修改密码
     * @param password
     * @param user_name
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/updatePwd"})
    public String updatePwd(@RequestParam("password")String password,@RequestParam("user_name")String user_name){
        int res = userservice.updatePwd(password,user_name);
        if (res == 0){
            return "更改失败";
        }else {
            return "更改成功";
        }
    }

    /**
     * 更改图片
     * @param files
     * @param user_name
     * @param request
     * @return
     */
    @RequestMapping("/updatePhoto")
    @ResponseBody
    public HashMap<String,String> updatePhoto(@RequestParam("file")MultipartFile files,
                              @RequestParam("user_name")String user_name,
                              HttpServletRequest request){
        HashMap<String,String> map = new HashMap<>();
        if(user_name!="") {
            //判断是否存在
            if (!files.isEmpty()) {
                //文件存放路径
                String path = "D:\\img";
                //文件名称
                String name = String.valueOf(new Date().getTime() + "_" + files.getOriginalFilename());
                File destFile = new File(path, name);
                if (!destFile.getParentFile().exists()){
                    destFile.getParentFile().mkdirs();
                }
                //存入数据库的路径
                String file = path + name;
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + name;
                String filename = request.getScheme() + "://" + request.getServerName() + ":"+"/static/"+name;
                //转存文件
                try {
                    files.transferTo(destFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                map.put("path2",filename);
                map.put("path", path);
                map.put("name", name);
                map.put("url", url);
                int res = userservice.updatePhoto(filename, user_name);
                if (res == 0) {
                    map.put("judge", "失败");
                    return map;
                } else {
                    map.put("judge", "成功");
                    return map;
                }
            } else {
                return map;
            }
        }else {
           map.put("judge","失败请给用户名");
            return map;
        }
    }

    /**
     * 根据user_name查询信息
     * @param user_name
     * @return
     */
    @RequestMapping(value = "/userbyid")
    @ResponseBody
    public User queryUser_Id(@RequestParam("user_name") String user_name){
        User users = userservice.queryUserById(user_name);
        return users;
    }

}
